package com.mcptt.config.user.profile;

import com.cloudptt.api.comm.Const;
import com.cloudptt.api.product.func.addr.IAddrDefaultOp;
import com.cloudptt.api.product.func.call.CallAttr;
import com.cloudptt.api.product.log.Log;
import com.mcptt.config.AbstractConfigFile;
import com.mcptt.config.callback.IParserCallback;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.BootStrapSvrInfo;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.config.user.profile.sub.Common;
import com.mcptt.config.user.profile.sub.OnNetwork;
import com.mcptt.config.user.profile.sub.Ruleset;
import com.mcptt.config.user.profile.sub.sub.sub.Entry;
import com.mcptt.config.user.profile.sub.sub.sub.PrivateCallURI;
import com.mcptt.db.DBAdapter;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.ConfigFileInfo;
import com.mcptt.db.model.GroupInfo;
import com.mcptt.db.model.UserInfo;
import com.mcptt.notify.xcap.XcapDoc;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;

public class UserProfile extends AbstractConfigFile
{
//	public static final int FileType = 3;

	public static final String FileName_Mcptt = "org.3gpp.mcptt.user-profile";
	public static final String FileName_Mcvideo = "org.3gpp.mcvideo.user-profile";
	public static final String FileName_Mcdata = "org.3gpp.mcdata.user-profile";
	//    private static final String FilePath = "//config//";
	public static final String Name = "mcptt-user-profile";
	private static final String Name_XuiURI = "XUI-URI";
	//	private static final String Name_SchemaLocation = "schemaLocation";
	//	private static final String Name_Xsi = "xmlns:xsi";
	//	private static final String Name_Xmlns = "xmlns";
	private static final String Name_Status = "Status";

	private String xuiURI = "";
	//	private String schemaLocation = null;
	//	private String xsi = null;
	//	private String xmlns = null;

	private String status = null;
	private Common common = null;
	private OnNetwork onNetwork = null;
	private Ruleset ruleset = null;

	private int mcType = UserInfo.McType_Ptt;
	private IParserCallback parserCallback = null;
	private SysConfig sysConfig = null;
	private IAddrDefaultOp addrDefaultOp = null;


	public UserProfile(int mcType, McIdInfo mcIdInfo, DBAdapter dbOperator, SysConfig sysConfig, IParserCallback parserCallback, IAddrDefaultOp addrDefaultOp)
	{
		super(dbOperator);
		this.parserCallback = parserCallback;
		this.addrDefaultOp = addrDefaultOp;
		this.mcType = mcType;
		Log.debug(this.getClass(), "UserProfile mcType = " + mcType);
		this.sysConfig = sysConfig;
		String fileName = FileName_Mcptt;
//		this.info = readFromDb(fileName);
//		Log.debug(this.getClass(), "UserProfile info = " + info);
//		if(info == null)
//		{
//			String id = getId(mcType,mcIdInfo);
//			if( id != null) {
//				String accessToken = mcIdInfo.getAccessToken();
//				XcapDoc doc = XcapDoc.getUserProfileXcapDoc(mcType, id);
//				String cmsUrl = sysConfig.getBootStrapSvr().toInitHttpUrl();
//				runReadFromSvrThread(doc, cmsUrl, accessToken, parserCallback);
//			}
//		}
//		else {
//			parse(info);
//		}
//		parse(info);
	}

	private String getId(int mcType,McIdInfo mcIdInfo)
	{
		if(mcIdInfo != null)
		{
			if(mcType == CallAttr.McType_McVideo)
			{
				return mcIdInfo.getMcvideoId();
			}
			else if(mcType == CallAttr.McType_McData)
			{
				return mcIdInfo.getMcvideoId();
			}
			else
			{
				return mcIdInfo.getMcpttId();
			}
		}
		return null;
	}
//	private void notifyFailed(IParserCallback callback,String errStr)
//	{
//		if(callback != null)
//		{
//			callback.parserNotifyFailed(errStr);
//		}
//	}
	public void parse(ConfigFileInfo info)
	{
		if(info == null)
		{
			return;
		}
		SAXBuilder builder = new SAXBuilder();//实锟斤拷JDOM锟斤拷锟斤拷锟斤拷
		//	File file = new File(Environment.getExternalStorageDirectory()+FilePath,FileName);
		//	FileInputStream fis = new FileInputStream(file);
		String content = info.getContent();
		InputStream strIs = new  ByteArrayInputStream(content.getBytes());

		try {
			InputStreamReader isr = new InputStreamReader(strIs, "UTF-8");
			Document document = builder.build(isr);
//			Document document = builder.build(strIs);
			Element root = document.getRootElement();//锟斤拷酶锟斤拷诘锟�<bookstore>
			if(root == null)
			{
				return;
			}
			xuiURI = root.getAttributeValue(Name_XuiURI);
			//		Namespace ns = root.getNamespace();
			//		schemaLocation = root.g.getAttributeValue(Name_SchemaLocation, ns);
			//		schemaLocation = root.getAttributeValue(Name_SchemaLocation);
			//		xsi = root.getAttributeValue(Name_Xsi);
			//		xmlns = root.getAttributeValue(Name_Xmlns);

			List<Element> list = root.getChildren();//锟斤拷酶锟斤拷诘锟斤拷锟接节碉拷
			for(Element elem:list)
			{
				String name = elem.getName();
				Log.debug(this.getClass(), "name = " + name);
				if(name == null
						|| name.length() <= 0)
				{
					return;
				}
				if(name.equals(Name_Status))
				{
					this.status = elem.getText();
				}
				else if(name.equals(Common.Name))
				{
					common = new Common();
					common.parse(elem);
				}
				else if(name.equals(OnNetwork.Name))
				{
					onNetwork = new OnNetwork();
					onNetwork.parse(mcType,elem);
				}
				else if(name.equals(Ruleset.Name))
				{
					ruleset = new Ruleset();
					ruleset.parse(elem);
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			String fileName = FileName_Mcptt;
			notifyFailed(parserCallback,fileName,"UserProfile parse Exception = " + e);
		}

	}
	public boolean checkMustParamOk()
	{
    	return true;
	}

	private void saveLoginUseName()
	{

		if(this.sysConfig == null)
		{
			return;
		}
		if(common != null
				&& common.getUserAlias() != null
				&& common.getUserAlias().getAliasEntry() != null)
		{
			String name = common.getUserAlias().getAliasEntry();
			sysConfig.setMcpttLoginName(name);
		}
	}

	private void saveUserInfoList(int type)
	{
		if(this.dbOperator == null
			|| CallAttr.McType_McPtt != type)
		{
			return;
		}

		if(CallAttr.McType_McPtt == type) {
			this.dbOperator.deleteAllUserInfo();
		}
		if(common != null
				&& common.getPrivateCall() != null
				&& common.getPrivateCall().getPrivateCallList() != null)
		{
			List<PrivateCallURI> list = common.getPrivateCall().getPrivateCallList();
			if(list != null
					&& list.size() > 0)
			{
				for(Iterator<PrivateCallURI> iter = list.iterator();iter.hasNext();)
				{
					PrivateCallURI callUri = iter.next();
					String urlEntry = callUri.getUriEntry();
					String name = callUri.getDisplayName();
					String addrId = AddrInfo.toNumFromSipUrl(urlEntry);
					UserInfo info = new UserInfo(AddrInfo.UserType_User,name,addrId);
					info.updateMcxId(type,urlEntry);
					this.dbOperator.updateUserInfo(info);
				}
			}
		}
	}

	private void saveEmergencyCall()
	{

		if(this.sysConfig == null)
		{
			return;
		}
		if(common != null
				&& common.getPrivateCall() != null
				&& common.getPrivateCall().getEmergencyCall() != null)
		{
			String privateRecipient = common.getPrivateCall().getEmergencyCall().getPrivateRecipient();
			String groupInitiation = common.getPrivateCall().getEmergencyCall().getGroupInitiation();
			sysConfig.getUserConfig().setEmergencyCall(privateRecipient,groupInitiation);
		}
	}

	private void saveGroupInfoList(int type)
	{
		Log.debug(this.getClass(), "saveGroupInfoList type = " + type);
		if(this.dbOperator == null
				|| CallAttr.McType_McPtt != type)
		{
			return;
		}
		if(CallAttr.McType_McPtt == type) {
			this.dbOperator.deleteAllGroupInfo();
		}
		if(onNetwork != null
				&& onNetwork.getMcGroupInfo() != null
				&& onNetwork.getMcGroupInfo().getEntryList() != null)
		{
			List<Entry> list = onNetwork.getMcGroupInfo().getEntryList();
			Log.debug(this.getClass(), "saveGroupInfoList list = " + list);
			if(list != null
					&& list.size() > 0)
			{
				String defaultGroupId = sysConfig.getDefaultGroupID();
				boolean isHasDef = false;
//				for(Iterator<Entry> iter = list.iterator();iter.hasNext();)
				for(int i = 0;i < list.size(); i++)
				{
					Entry callUri = list.get(i);
					String urlEntry = callUri.getUriEntry();
					String name = callUri.getDisplayName();
					String addrId = AddrInfo.toNumFromSipUrl(urlEntry);
					GroupInfo info = new GroupInfo(addrId,name,urlEntry);
					if(info.isSameOne(defaultGroupId))
					{
						info.setIsAffiliation(true);
						isHasDef = true;
						if(addrDefaultOp != null) {
							addrDefaultOp.setDefaultGroupInfo(info);
						}
					}
					if(!isHasDef
						&& i == list.size() -1)
					{
						info.setIsAffiliation(true);
						if(addrDefaultOp != null) {
							addrDefaultOp.setDefaultGroupInfo(info);
						}
					}
					Log.debug(this.getClass(), "saveGroupInfoList info = " + info);
					this.dbOperator.addGroupInfo(info);
				}
			}
		}
		
//		List<UserInfo> list = dbOperator.getAddressList(UserInfo.UserType_Group);
//		Log.debug(this.getClass(), "saveGroupInfoList over list = " + list);
	}

	public String toString()
	{
		StringBuffer strBuf = new StringBuffer("\r\n");
		strBuf.append("<").append(Name);
		strBuf.append(" ").append(Name_XuiURI).append("=\"").append(xuiURI).append("\" ");
		//		strBuf.append(" ").append(Name_SchemaLocation).append("=\"").append(schemaLocation).append("\" ");
		//		strBuf.append(" ").append(Name_Xsi).append("=\"").append(xsi).append("\" ");
		//		strBuf.append(" ").append(Name_Xmlns).append("=\"").append(xmlns).append("\" ");
		strBuf.append(">");

		strBuf.append("<").append(Name_Status).append(">");
		strBuf.append(status);
		strBuf.append("</").append(Name_Status).append(">").append("\r\n");
		strBuf.append(common);
		strBuf.append(onNetwork);
		strBuf.append(ruleset);
		strBuf.append("</").append(Name).append(">");

		return strBuf.toString();
	}

	@Override
	public void syncToSvr()
	{
		// TODO Auto-generated method stub

	}
	//    public Common getCommon()
	//    {
	//	return common;
	//    }
	//
	//    public OnNetwork getOnNetwork()
	//    {
	//	return onNetwork;
	//    }
	@Override
	public void saveInfoToDb()
	{
		// TODO Auto-generated method stub
		Log.debug(getClass(), "saveInfoToDb");
		if(this.dbOperator != null)
		{
//			this.addressDbOperator.deleteAllGroupUser();
		}
		saveLoginUseName();
		saveUserInfoList(mcType);
		saveEmergencyCall();
		saveGroupInfoList(mcType);
	}
}
